import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter_1800/pages/user/loginView.dart';
import 'package:flutter_1800/tools/AppUtil.dart';
import 'package:flutter_1800/tools/config.dart';
import 'package:flutter_1800/tools/storage.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

Dio dio = Dio();

class WebService {
  static String defaultErrMsg = "系统错误";

  // get
  static Future get(String url) async {
    Response response;
    try {
      Options options = Options();
      var token = await StorageUtil.getToken();

      options.headers = {"Authori-zation": token};
      var p = AppConfig.DOMAIN + "/mallapi" + url;
      print("path=" + p);
      response = await dio.get(p, options: options);
      return dealData(response);
    } catch (e) {
      EasyLoading.showError(defaultErrMsg);
      rethrow;
    }
  }

  // post
  static Future post(String url, Map params) async {
    Response response;
    try {
      Options options = Options();
      var token = await StorageUtil.getToken();

      options.headers = {"Authori-zation": token};
      if (params != null) {
        print("参数=" + jsonEncode(params));
      }

      response = await dio.post(AppConfig.DOMAIN + "/mallapi" + url,
          data: params, options: options);
      return dealData(response);
    } catch (e) {
      // EasyLoading.showError(defaultErrMsg);
      rethrow;
    }
  }

  ///dio 实现文件上传
  static Future uploadFile(url, String localImagePath, String suffix) async {
    ///创建Dio
    Dio dio = Dio();
    Options options = Options();

    Map<String, dynamic> map = {};
    // map["auth"] = "12345";
    // map["file"] =
    //     await MultipartFile.fromFile(localImagePath, filename: "xxx23.png");

    ///通过FormData
    FormData formData = FormData.fromMap(map);

    ///发送post
    Response response = await dio.post(
      AppConfig.DOMAIN + url, data: formData,

      ///这里是发送请求回调函数
      ///[progress] 当前的进度
      ///[total] 总进度
      onSendProgress: (int progress, int total) {
        print("当前进度是 $progress 总进度是 $total");
      },
    );

    var data = response.data;
    var res = data["data"];

    FormData form = FormData.fromMap({
      "Filename": "111" + suffix,
      "key": res["dir"] + res["key"] + suffix,
      "policy": res["policy"],
      "success_action_status": 200,
      "OSSAccessKeyId": res["accessid"],
      "signature": res["signature"],
      "x-oss-security-token": res["securityToken"],
      "file":
          MultipartFile.fromFileSync(localImagePath, filename: "111" + suffix)
    });

    ///服务器响应结果
    return res["host"] + "/" + res["dir"] + res["key"] + suffix;
  }

  //处理数据
  static dealData(Response response) {
    try {
      var data = response.data;
      if (data is String) {
        data = AppUtil.toJson(data);
      }
      int code = data["code"];

      if (code != 0) {
        if (code == 401) {
          // 未登录
          AppUtil.getTo(const LoginViewPage());
          throw Exception();
        }
        String msg = response.data['msg'];
        if (msg.isEmpty) {
          msg = defaultErrMsg;
        }
        EasyLoading.showError(msg);
        throw Exception();
      }
      return data["data"];
    } catch (e) {
      //Message.error(defaultErrMsg);
      rethrow;
    }
  }
}
